const mongoose = require("mongoose");
var User = require('../models/user.model');
var Admin = require('../models/admin.modle');
var jwt=require('jsonwebtoken');
//增加
exports.create = function(req, res, next) {
        const user = new User(req.body);
        user.save().then((data) => res.json(data));
    }
    //更改
exports.update = function(req, res, next) {
        var id = req.params.id;
        User.findByIdAndUpdate(id, { $set: req.body }, { new: false, upsert: false }).then((data) => res.json(data));
    }
    //根据id删除单条记录
exports.delete = function(req, res, next) {
        var id = req.params.id;
        User.findByIdAndDelete(id).then((data) => res.json(data));
    }
    //根据id删除多条记录
exports.deletes = function(req, res, next) {
        const ids = req.body.ids.split(',');
        if (ids.length > 0) {
            User.remove({ _id: { $in: ids } }).then(data => {
                console.log(data);
                res.json({ "message": "数据已成功删除!" });
            })
        }
    }
    //根据id查找
exports.selectbyId = function(req, res, next) {
        var id = req.params.id;
        User.findById(id).then((data) => res.json(data));
    }
    //分页
exports.list = function(req, res, next) {
    var page = req.body.page ? req.body.page : 1;
    var limit = req.body.rows ? req.body.rows : 10;

    var selectbyother = {};
    if (req.body.name && req.body.name.trim().length > 0) {
        selectbyother = {
            "name": new RegExp(req.body.name, 'i')
        }
    }

    User.paginate(selectbyother, { page: +page, limit: +limit }, function(err, result) {
        result.rows = result.docs;
        delete result.docs;
        res.json(result);
    });
}
exports.login= function(req,res,next){
    /* const user={
        id:1,
        name:'gcl',
        age:20
    } */
    Admin.findOne(req.body,(err,results)=>{
        //console.log(results);
        jwt.sign({results}, 'mySecretString',(err,token)=>{
            //console.log({token});
            var user=JSON.parse(JSON.stringify(results));
            delete user.password;
            user.token=token;

            res.json(user);
        });
    });

}